package com.myshoutui;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.myshout.CatalogItem;
import com.myshout.Client;
import com.myshout.ConsumerSplash;
import com.myshout.ImageFetcher;
import com.myshout.Offer;
import com.myshout.Store;
import com.myshout.StoreCatalog;
import com.myshout.Thing;
import com.myshout.android.commmon.MyLocation;
import com.myshout.android.commmon.MyLocation.LocationResult;
import com.myshout.android.commmon.Utils;
import com.myshoutui.manager.AnalyzedQuery;
import com.myshoutui.manager.MyShoutConsumerAsynTaskInterface;
import com.myshoutui.manager.MyShoutDataManager;

public class MyShoutDashboardActivity extends Activity implements
		MyShoutConsumerAsynTaskInterface, OnClickListener {

	ArrayList<Store> storesList = new ArrayList<Store>();
	public static HashMap<Long, Thing> allThings = new HashMap<Long, Thing>();
    public static Store selectedStore;
	SearchAdapter adapter;
	MyShoutDataManager app;
	MyShoutConsumerAsynTaskInterface mAsynListener = null;
	LinearLayout searchHolder;
	ImageView mCloseSearch;

	public Location location;
	private AnalyzedQuery analyzedSearchQuery;
	private MyLocation myLocation;
	private ProgressDialog progressDialog;
	Hashtable<String, ImageView> htImageViews;
	public static ConsumerSplash mConsumerSplash = null;

	SpecialsAdapter mSpecialAdapter = null;
	FavoritesAdapter mfavoriteAdapter = null;
	private EditText mSearchItem;
	private ImageView mSearchImg;

	// roger changes
	private GridView mSpecialScrollView;
	private GridView mFavoriteScrollView;
	private static LayoutInflater mInflater;
	TextView item_title;
	InputMethodManager inputManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity_dasboard);
		mSearchItem = (EditText) findViewById(R.id.search_list);
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		progressDialog = ProgressDialog.show(this, "", "Loading.....", true);
		// roger changes
		mInflater = LayoutInflater.from(getApplicationContext());
		item_title = (TextView) findViewById(R.id.special_item_title);
		item_title.requestFocus();
		mSpecialScrollView = (GridView) findViewById(R.id.special_horizontal_scroll);
		mFavoriteScrollView = (GridView) findViewById(R.id.favorite_horizontal_scroll);
		Client.setCurrency("USD", "$");
		LocationResult locationResult = new LocationResult() {
			@Override
			public void gotLocation(Location loc) {
				location = loc;
			}
		};
		myLocation = new MyLocation();
		myLocation.getLocation(getApplicationContext(), locationResult);

		mAsynListener = this;
		app = (MyShoutDataManager) getApplicationContext();
		app.setSearchResultChangeCallbackHandler(handler);
		htImageViews = new Hashtable<String, ImageView>();

		mSearchImg = (ImageView) findViewById(R.id.search_icon);
		ListView list = (ListView) findViewById(R.id.list);
		searchHolder = (LinearLayout) findViewById(R.id.searchboardholder);
		// Getting adapter by passing xml data ArrayList
		adapter = new SearchAdapter(this, storesList);
		list.setAdapter(adapter);
		mCloseSearch = (ImageView) findViewById(R.id.closesearch);
		mCloseSearch.setOnClickListener(this);
		mSearchImg.setOnClickListener(this);
		mSearchItem.setOnClickListener(this);
		
		// changes 28/07
		((TextView)findViewById(R.id.special_txt)).setOnClickListener(this);
		  ((TextView)findViewById(R.id.favorites_txt)).setOnClickListener(this);
		  
	}

	
	
	// roger changes
	public void clickView(View v) {
		switch (v.getId()) {
		case R.id.special_txt:
			 ((TextView)findViewById(R.id.special_txt)).setBackgroundDrawable(getResources().getDrawable(R.drawable.button_active_state));
			   ((TextView)findViewById(R.id.favorites_txt)).setBackgroundDrawable(getResources().getDrawable(R.drawable.button_idle_state));
			   item_title.setText(getString(R.string.special_txt));
			   ((TextView) findViewById(R.id.no_item_favorite))
			     .setVisibility(View.GONE);
			   if (((TextView) findViewById(R.id.no_item)).getText().toString()
			     .length() > 0) {
			    ((TextView) findViewById(R.id.no_item))
			      .setVisibility(View.VISIBLE);
			   }
			   mFavoriteScrollView.setVisibility(View.GONE);
			   mSpecialScrollView.setVisibility(View.VISIBLE);
			   ((View) findViewById(R.id.view2)).setVisibility(View.VISIBLE);
			   ((View) findViewById(R.id.view3)).setVisibility(View.GONE);
			break;
		case R.id.favorites_txt:
			((TextView)findViewById(R.id.special_txt)).setBackgroundDrawable(getResources().getDrawable(R.drawable.button_idle_state));
			   ((TextView)findViewById(R.id.favorites_txt)).setBackgroundDrawable(getResources().getDrawable(R.drawable.button_active_state));
			   item_title.setText(app.getUsername());
			   ((TextView) findViewById(R.id.no_item)).setVisibility(View.GONE);
			   if (((TextView) findViewById(R.id.no_item_favorite)).getText()
			     .toString().length() > 0) {
			    ((TextView) findViewById(R.id.no_item_favorite))
			      .setVisibility(View.VISIBLE);
			   }
			   mFavoriteScrollView.setVisibility(View.VISIBLE);
			   mSpecialScrollView.setVisibility(View.GONE);
			   ((View) findViewById(R.id.view2)).setVisibility(View.GONE);
			   ((View) findViewById(R.id.view3)).setVisibility(View.VISIBLE);
			break;
		}
	}

	// private void addSpecialViews()
	// {
	// LayoutInflater mInflate = this.getLayoutInflater();
	// LinearLayout layout = new LinearLayout(this);
	// LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
	// (LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
	// layout.setLayoutParams(params);
	// layout.setOrientation(LinearLayout.HORIZONTAL);
	// List<Store> mStoresList = mConsumerSplash.getStores();
	// for (int i = 0; i < mStoresList.size(); i++)
	// {
	// View view = mInflate.inflate(R.layout.dashboard_special_singleitem,null);
	// TextView mItemName = (TextView)view.findViewById(R.id.item_name);
	// TextView mItemOffer = (TextView)view.findViewById(R.id.discount_offer);
	// ImageView ItemImage = (ImageView)view.findViewById(R.id.item_src);
	// TextView mItemRestName =
	// (TextView)view.findViewById(R.id.restarent_name);
	// TextView mItemOfferExp = (TextView)view.findViewById(R.id.offer_exp);
	// TextView mItemPrice = (TextView)view.findViewById(R.id.price);
	//
	//
	// mItemName.setText(mStoresList.get(i).getName()); // item name
	// // mItemOffer.setText(mStoresList.get(i).+"off  "); // item discount
	// // ItemImage.setImageResource(resId); // item image
	// mItemRestName.setText("Gourmet Max Restarent "+i); // Restaurant name
	// mItemOfferExp.setText("1.00"+"hr");
	// mItemPrice.setText("$"+i);
	// layout.addView(view);get
	// }
	// mSpecialScrollView.addView(layout);
	// }

	@Override
	protected void onStart() {
		super.onStart();
		MyShoutDataManager app = (MyShoutDataManager) getApplicationContext();
		app.getConsumerDashboard("", app.getUserId(), 37.5483, -121.9875,
				handler);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		myLocation.cancelTimer();
	}

	@Override
	public void startTask() {
		// TODO Auto-generated method stub

	}

	@Override
	public void endTask(Object result) {
	}

	@Override
	public Object executeTask(Object... task) {
		// TODO Auto-generated method stub
		analyzedSearchQuery = app.find("Google", task[0].toString(), null,
				location);
		return null;
	}

	private synchronized ArrayList<Store> mergeResults(ArrayList<Store> list1,
			ArrayList<Store> list2) {
		for (Store s : list2) {
			if (s.getId() != null && list1.contains(s))
				continue;
			list1.add(s);
		}
		return list1;
	}

	void loadIcon(ImageView imageView, Object s) {
		if (s == null)
			return;
		String url = null;
		long id = 0;
		String imageFile = null;
		/*
		 * if (s.getActiveStatus() == 0) {
		 * imageView.setImageResource(R.drawable.closed); return; }
		 */
		if (s instanceof Thing) {
			url = ((Thing) s).getImageUrl();
			id = ((Thing) s).getId();
			imageFile = ((Thing) s).getImageFile();

		}

		if (s instanceof Store) {
			url = ((Store) s).getImageUrl();
			id = ((Store) s).getId();
			imageFile = ((Store) s).getImageFile();

		}

		Drawable drawable = null;
		Object object = Client.getFromMemCache(url == null ? "" : url);
		if (object != null && object instanceof Drawable) {
			drawable = (Drawable) object;
			imageView.setImageDrawable(drawable);
			return;
		}

		imageView.setImageResource(R.drawable.store_default);

		String viewId = imageView.toString();
		imageView.setTag(url);
		htImageViews.put(viewId, imageView);

		String fileUrl = Utils.getFileUrl(imageFile);
		new ImageFetcher(url, fileUrl, id, viewId, handler).start();
	}

	// Handler that receives messages from other threads
	final Handler handler = new Handler() {

		public void handleMessage(Message message) {

			try{
			if (progressDialog != null && progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			}catch(IllegalStateException ie){
				
			}
			switch (message.what) {

			case MyShoutDataManager.MSG_GOT_DASHBOARD:
				Log.d("Splash: ",
						Client.getGson().toJson((ConsumerSplash) message.obj));
				mConsumerSplash = (ConsumerSplash) message.obj;
				

				// roger changes
				// addSpecialViews();
				// addFavoriteslViews();
				List<StoreCatalog> mFavoritesList = mConsumerSplash.getFavorites();
				List<StoreCatalog> mStoresList = mConsumerSplash.getStores();
				List<Offer> mOffers = new ArrayList<Offer>();
				List<Thing> mThings = new ArrayList<Thing>();

				
                allThings.clear();
				for (StoreCatalog storeData : mStoresList) {
					List<Offer> offerData = storeData.getOffers();
					List<CatalogItem> thingData = storeData.getCatalog();
					if (thingData != null) {
						for (Thing t : thingData)
							allThings.put(t.getId(), t);
					}

					if (offerData != null) {

						for (Offer data : offerData) {
							data.setStore(storeData.getStore().getId());
						}

						mOffers.addAll(offerData);
					}
				}

				if (mOffers != null && mOffers.size() != 0) {
					((TextView) findViewById(R.id.no_item))
							.setVisibility(View.GONE);
					((TextView) findViewById(R.id.no_item)).setText("");
					mSpecialAdapter = new SpecialsAdapter(mOffers);
					mSpecialScrollView.setAdapter(mSpecialAdapter);
				} else {
					((TextView) findViewById(R.id.no_item))
							.setText("Currently No Offers");
					((TextView) findViewById(R.id.no_item))
							.setVisibility(View.VISIBLE);
				}

				if (mFavoritesList != null && mFavoritesList.size() != 0) {
					((TextView) findViewById(R.id.no_item_favorite))
							.setText("");
					((TextView) findViewById(R.id.no_item_favorite))
							.setVisibility(View.GONE);
					mfavoriteAdapter = new FavoritesAdapter(mFavoritesList);
					mFavoriteScrollView.setAdapter(mfavoriteAdapter);
				} else {
					((TextView) findViewById(R.id.no_item_favorite))
							.setText("No Favorites Items");
					((TextView) findViewById(R.id.no_item_favorite))
							.setVisibility(View.VISIBLE);
				}

				break;

			case Client.MSG_UPDATE_IMAGE:
				Bundle b = message.peekData();
				if (b == null)
					return;

				String viewId = b.getString(Client.VIEW_ID);
				String url = b.getString(Client.URL);

				if (message.obj instanceof Drawable && viewId != null
						&& url != null) {
					Drawable drawable = (Drawable) message.obj;
					ImageView imageView = (ImageView) htImageViews.get(viewId);
					if (drawable != null) {
						Client.putInMemCache(url, drawable);
						if (imageView != null) {
							String myUrl = (String) imageView.getTag();
							if (url.equals(myUrl)) {
								imageView.setImageDrawable(drawable);

							}
						}
					} else {
						if (imageView != null) {
							// imageView.setImageResource(R.drawable.thing);
						}
					}
				}
				break;

			case MyShoutDataManager.MSG_SEARCH_YELP:
				if (message.obj != null) {
					if (((ArrayList<Store>) message.obj).size() == 0) {
						Toast.makeText(getApplicationContext(),
								"No Results Found!!!", Toast.LENGTH_LONG)
								.show();
						return;

					}
					storesList.clear();
					mergeResults(storesList, (ArrayList<Store>) message.obj);
					/*
					 * if (analyzedSearchQuery.getPresentationOrder() ==
					 * OUTPUT_ORDERING.SORT_BY_DISTANCE) adapter.sort(new
					 * AscendingDistanceComparator()); else if
					 * (analyzedSearchQuery.getPresentationOrder() ==
					 * OUTPUT_ORDERING.SORT_BY_RATING) adapter.sort(new
					 * DescendingRatingComparator()); else if
					 * (analyzedSearchQuery.getPresentationOrder() ==
					 * OUTPUT_ORDERING.SORT_BY_PRICE) adapter.sort(new
					 * DescendingRatingComparator()); else adapter.sort(new
					 * AscendingDistanceComparator());
					 */
					adapter.notifyDataSetChanged();
					ExpandCollapseAnimation animation = null;
					animation = new ExpandCollapseAnimation(searchHolder, 1000,
							0);
					searchHolder.startAnimation(animation);

				}

				// setTitle(getString(R.string.search_results_for_) +
				// analyzedSearchQuery.toString());

				break;
			}
		}
	};

	public static List<Offer> getOfferForStore(Long storeId) {
		for(StoreCatalog sC : mConsumerSplash.getStores()){
			if(sC.getStore().getId().equals(storeId)){
				if(sC.getOffers()!=null){
					return sC.getOffers();
				}
			}
		}
		
		/*if (mConsumerSplash.getOffers() != null
				&& mConsumerSplash.getOffers().size() > 0)
			return mConsumerSplash.getOffers().get(storeId);*/
		return null;
	}


	// roger changes
	private class SpecialsAdapter extends BaseAdapter {
		List<Offer> mOffersList = null;
		List<Store> mFav = null;

		public SpecialsAdapter(List<Offer> mOffersList) {
			this.mOffersList = mOffersList;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
//			return mOffersList.size();
			return mOffersList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position,  View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			// A ViewHolder keeps references to children views to avoid
			// unneccessary calls
			// to findViewById() on each row.
			SpecialViewHolder holder;

			// When convertView is not null, we can reuse it directly, there is
			// no need
			// to reinflate it. We only inflate a new View when the convertView
			// supplied
			// by ListView is null.
			if (convertView == null) {
				convertView = mInflater.inflate(
						R.layout.dashboard_special_singleitem, null);

				// Creates a ViewHolder and store references to the two children
				// views
				// we want to bind data to.
				holder = new SpecialViewHolder();
				holder.itemName = (TextView) convertView
						.findViewById(R.id.item_name);
				holder.storeName = (TextView) convertView
						.findViewById(R.id.restarent_name);
				holder.itemOffer = (TextView) convertView
						.findViewById(R.id.offer_exp);
				holder.itemPrice = (TextView) convertView
						.findViewById(R.id.price);
				holder.discountOffer = (TextView) convertView
						.findViewById(R.id.discount_offer);
				holder.storeImg = (ImageView) convertView
						.findViewById(R.id.item_src);
				holder.heartIcon = (ImageView) convertView
						.findViewById(R.id.heart_icon);
				convertView.setTag(holder);
			} else {
				// Get the ViewHolder back to get fast access to the TextView
				// and the ImageView.
				holder = (SpecialViewHolder) convertView.getTag();
			}

			convertView.setTag(R.layout.main_activity_dasboard, mOffersList.get(position).getStore());
			

			// Bind the data efficiently with the holder.
//			 holder.itemName.setText(getStoreName(mStoresList.get(position).getStore()));

			Thing thing = allThings.get(mOffersList.get(position).getThing());
			final Store storeData = getStoreName(mOffersList.get(position).getStore());
			loadIcon(holder.storeImg, thing);
            
			holder.itemName.setText(thing.getName());
			if (storeData != null)
				holder.storeName.setText(storeData.getName());
			if (storeData != null)
				holder.itemPrice.setText(""
						+ Client.formatMoney(storeData.getCurrency(),
								mOffersList.get(position).getPaidValue()));
			// holder.discountOffer.setText();
			holder.itemOffer.setText(""
					+ Client.getFriendlyTimeDiff(mOffersList.get(position)
							.getStartDate(), mOffersList.get(position)
							.getEndDate()));
			holder.discountOffer.setText(mOffersList.get(position).getTitle());
			holder.discountOffer.setBackgroundColor(getResources().getColor(
					R.color.dark_red));

			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					if (storeData != null
							&& storeData.getOwner() != null) {
					Intent data = new Intent(getApplicationContext(),
							MyShoutStoreViewActivity.class);
					selectedStore =  storeData;
					data.putExtra("STORED", Long.parseLong(arg0.getTag(R.layout.main_activity_dasboard).toString()));
					startActivity(data);
				}
					else{
						Intent data = new Intent(getApplicationContext(),
								MyShoutNonFeaturedStoreViewActivity.class);
						startActivity(data);
						
					}
				}
			});

			return convertView;
		}

		
		
		
			}

	
	public static Store getStoreName(Long store) {
		
		for (StoreCatalog data : mConsumerSplash.getStores()) {
			Log.e("", "comparing  "+ store+"   "+ data.getStore().getId());

			if (data.getStore().getId().equals(store)) {
				return data.getStore();
			}
		}
		return null;

	}

	public static Offer getOfferByThing(Long thing,Long store){
		try{
		List<Offer> offers = getOfferForStore(store);
		for(Offer data : offers){
			if(data.getThing()==thing){
				return data;
			}
				
		}
		}catch (Exception e) {
			return null;
		}
		return null;

		
		
	}
	public static List<Thing> getThings(Long store){
		List<Thing> data = new ArrayList<Thing>();
		try{
			for(StoreCatalog sC : mConsumerSplash.getStores()){
				if(sC.getStore().getId()==store){
					for(CatalogItem cI : sC.getCatalog())
						data.add(cI);
				}
			}
			/*for(Thing t : mConsumerSplash.getCatalogs().get(store)){
				data.add(t);
			}*/
		return data;
		}catch (Exception e) {
            return null;
		}
		
	}
	
	public static List<Thing> getThingByCategory(String category,Long store){
		ArrayList<Thing> categoryData = new ArrayList<Thing>();
		for(StoreCatalog data : mConsumerSplash.getStores()){
			if(data.getStore().getId() == store){
				for(CatalogItem cI : data.getCatalog()){
					if(cI.getCategory()!=null && cI.getCategory().equalsIgnoreCase(category)){
						categoryData.add(cI);
					}
				}

			}
		}
		
		
		/*for(Thing data: mConsumerSplash.getCatalogs().get(store)){
			if(data.getCategory()!=null && data.getCategory().equalsIgnoreCase(category)){
				categoryData.add(data);
			}
		}*/
		return categoryData;
	}
	
	public static ArrayList<String> getCategoryCount(Long store){
		try{
		ArrayList<String> categories = new ArrayList<String>();
		

		for(StoreCatalog data : mConsumerSplash.getStores()){
			if(data.getStore().getId() == store){
				for(CatalogItem cI : data.getCatalog())
					categories.add(cI.getCategory());
		
			}
		}
		
		
		/*for(Thing data : mConsumerSplash.getCatalogs().get(store)){
			
			if(!categories.contains(data.getCategory())){
			categories.add(data.getCategory());
			}
		}*/
		return categories;
		}catch (Exception e) {
			return null;
		}
	}
	
	class SpecialViewHolder {
		TextView itemName;
		TextView storeName;
		TextView itemOffer;
		TextView itemPrice;
		TextView discountOffer;
		ImageView storeImg;
		ImageView heartIcon;
	}

	// roger changes
	private class FavoritesAdapter extends BaseAdapter {
		List<StoreCatalog> mFavoriteStoresList = null;
		DecimalFormat df = new DecimalFormat("#.#");

		public FavoritesAdapter(List<StoreCatalog> mFavoritesList) {
			this.mFavoriteStoresList = mFavoritesList;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mFavoriteStoresList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			// A ViewHolder keeps references to children views to avoid
			// unneccessary calls
			// to findViewById() on each row.
			ViewHolder holder;

			// When convertView is not null, we can reuse it directly, there is
			// no need
			// to reinflate it. We only inflate a new View when the convertView
			// supplied
			// by ListView is null.
			if (convertView == null) {
				convertView = mInflater.inflate(
						R.layout.dashboard_favorites_item, null);

				// Creates a ViewHolder and store references to the two children
				// views
				// we want to bind data to.
				holder = new ViewHolder();
				holder.miles = (TextView) convertView
						.findViewById(R.id.miles_txt);
				holder.storeName = (TextView) convertView
						.findViewById(R.id.favorite_restarent_name);
				holder.itemDesc = (TextView) convertView
						.findViewById(R.id.favorite_desc);
				holder.itemDiscount = (TextView) convertView
						.findViewById(R.id.favorite_discount_offer);
				holder.featuredStore = (ImageView) convertView
						.findViewById(R.id.icon);
				holder.favoriteStoreImg = (ImageView) convertView
						.findViewById(R.id.favorite_item_src);
				convertView.setTag(holder);
			} else {
				// Get the ViewHolder back to get fast access to the TextView
				// and the ImageView.
				holder = (ViewHolder) convertView.getTag();
			}
			convertView.setTag(R.layout.main_activity_dasboard, mFavoriteStoresList.get(position).getStore().getId());
			loadIcon(holder.favoriteStoreImg, mFavoriteStoresList.get(position));
			double distance = 0.0d;
			if (location != null
					& mFavoriteStoresList.get(position).getStore().getLatitude() != null
					&& mFavoriteStoresList.get(position).getStore().getLongitude() != null) {
				distance = Utils.distanceInMiles(
						mFavoriteStoresList.get(position).getStore().getLongitude(),
						mFavoriteStoresList.get(position).getStore().getLatitude(),
						location.getLongitude(), location.getLatitude());
				holder.miles.setText(df.format(distance) + " mi.");

				if (mFavoriteStoresList.get(position).getStore().getDeliveryAvailable() == 1) {
					holder.miles.setText("Delivers");
				}
			} else {
				holder.miles.setText(df.format(distance) + " unk.");
			}

			// Bind the data efficiently with the holder.
			if (mFavoriteStoresList.get(position) != null
					&& mFavoriteStoresList.get(position).getStore().getName() != null) {
				holder.storeName.setText(
						mFavoriteStoresList.get(position).getStore().getName());
			}
			if (mFavoriteStoresList.get(position) != null
					&& mFavoriteStoresList.get(position).getStore().getDescription() != null) {
				holder.itemDesc.setText(mFavoriteStoresList.get(position).getStore().getDescription());
				Log.e("aaaaaa", ""
						+ mFavoriteStoresList.get(position).getStore().getDescription());
			}
			if (mFavoriteStoresList.get(position) != null
					&& mFavoriteStoresList.get(position).getStore().getOwner() == null) {
				holder.featuredStore.setVisibility(View.INVISIBLE);
			}

			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					if (mFavoriteStoresList.get(position) != null
							&& mFavoriteStoresList.get(position).getStore().getOwner() != null) {

					Intent data = new Intent(getApplicationContext(),
						MyShoutStoreViewActivity.class);
					selectedStore = mFavoriteStoresList.get(position).getStore();
				data.putExtra("STORED", Long.parseLong(arg0.getTag(R.layout.main_activity_dasboard).toString()));
				startActivity(data);
		}else{

			Intent data = new Intent(getApplicationContext(),
					MyShoutNonFeaturedStoreViewActivity.class);
			startActivity(data);
			
		
		}
				}
			});

			List<Offer> offer = getOfferForStore(mFavoriteStoresList.get(
					position).getStore().getId());
			// Bind the data efficiently with the holder.
			if (offer != null && offer.size() > 0) {
				// holder.itemDiscount.setText("" +"" +
				// MyShoutConsumerUtil.getFriendlyTimeDiff(mOffersList.get(position).getStartDate(),
				// mOffersList.get(position).getEndDate()));
				holder.itemDiscount.setBackgroundColor(getResources().getColor(
						R.color.dark_red));
			}
			return convertView;
		}

		private class ViewHolder {
			TextView miles;
			TextView storeName;
			TextView itemDesc;
			TextView itemDiscount;
			ImageView featuredStore;
			ImageView favoriteStoreImg;
		}

	}

	@Override
	public void onClick(View v) {

		if (v.getId() == R.id.search_icon) {
			if (mSearchItem.getText().toString().trim().length() == 0) {
				return;
			}

			// TODO: Support lookup by just address and no GPS in future
			analyzedSearchQuery = app.find("Google", mSearchItem.getText()
					.toString().trim(), null, location);
			progressDialog = ProgressDialog.show(
					this,
					"",
					getString(R.string.searching_for_)
							+ analyzedSearchQuery.toString(), true);
			searchHolder.setVisibility(View.VISIBLE);

			// roger changes
			((LinearLayout) findViewById(R.id.btn_layout))
					.setVisibility(View.GONE);
			((RelativeLayout) findViewById(R.id.layout_item))
					.setVisibility(View.GONE);

		} else if (v.getId() == R.id.closesearch) {

			ExpandCollapseAnimation animation = null;
			animation = new ExpandCollapseAnimation(searchHolder, 1000, 1);
			searchHolder.startAnimation(animation);

			// roger changes
			((LinearLayout) findViewById(R.id.btn_layout))
					.setVisibility(View.VISIBLE);
			((RelativeLayout) findViewById(R.id.layout_item))
					.setVisibility(View.VISIBLE);
		}else if (v.getId() == R.id.special_txt) 
		{
			((TextView)findViewById(R.id.special_txt)).setBackgroundDrawable(getResources().getDrawable(R.drawable.button_active_state));
			   ((TextView)findViewById(R.id.favorites_txt)).setBackgroundDrawable(getResources().getDrawable(R.drawable.button_idle_state));
			   item_title.setText(getString(R.string.special_txt));
			   ((TextView) findViewById(R.id.no_item_favorite))
			     .setVisibility(View.GONE);
			   if (((TextView) findViewById(R.id.no_item)).getText().toString()
			     .length() > 0) {
			    ((TextView) findViewById(R.id.no_item))
			      .setVisibility(View.VISIBLE);
			   }
			   mFavoriteScrollView.setVisibility(View.GONE);
			   mSpecialScrollView.setVisibility(View.VISIBLE);
			   ((View) findViewById(R.id.view2)).setVisibility(View.VISIBLE);
			   ((View) findViewById(R.id.view3)).setVisibility(View.GONE);
		}else if (v.getId() == R.id.favorites_txt) {
			((TextView)findViewById(R.id.special_txt)).setBackgroundDrawable(getResources().getDrawable(R.drawable.button_idle_state));
			   ((TextView)findViewById(R.id.favorites_txt)).setBackgroundDrawable(getResources().getDrawable(R.drawable.button_active_state));
			   item_title.setText(app.getUsername());
			   ((TextView) findViewById(R.id.no_item)).setVisibility(View.GONE);
			   if (((TextView) findViewById(R.id.no_item_favorite)).getText()
			     .toString().length() > 0) {
			    ((TextView) findViewById(R.id.no_item_favorite))
			      .setVisibility(View.VISIBLE);
			   }
			   mFavoriteScrollView.setVisibility(View.VISIBLE);
			   mSpecialScrollView.setVisibility(View.GONE);
			   ((View) findViewById(R.id.view2)).setVisibility(View.GONE);
			   ((View) findViewById(R.id.view3)).setVisibility(View.VISIBLE);
	}

	}
}
